package cn.newgrand.netcall.expert.transcript;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.util.StringUtils;

import cn.newgrand.netcall.util.StringUtil;
import cn.newgrand.netcall.expert.transcript.ChatTranscript;
import cn.newgrand.netcall.expert.transcript.ChatTranscripts;
import cn.newgrand.netcall.expert.transcript.HistoryMessage;
import cn.newgrand.smackx.specialist.ExpertManager;
import cn.newgrand.smackx.specialist.packet.TranscriptIQ;


public class TranscriptManager {
	
	private static DateFormat FORMATTER;

    static {
        FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
    }
	
    /**
     * 根据咨询开始时间 结束时间 和咨询者jid查询出聊天记录
     * @param jid 咨询者jid
     * @param startTime 咨询开始时间
     * @param endTime 咨询结束时间
     */
	public String getRoomTranscript(String jid,long startTime,long endTime){
		if(jid.indexOf("@") == -1){
			jid = jid + "@" + SparkManager.getConnection().getServiceName();
		}
		if(jid.lastIndexOf("/") != -1){
			jid = jid.substring(0, jid.lastIndexOf("/"));
		}
		StringBuilder builder = new StringBuilder();
		ChatTranscript chatTranscript = ChatTranscripts.getChatTranscript(jid);
		List<HistoryMessage> historyMessages= chatTranscript.getMessages();
		for(HistoryMessage historyMessage : historyMessages){
			long logTime = historyMessage.getDate().getTime();
			if(logTime > startTime && logTime < endTime){
				builder.append("<message>");
	            builder.append("<to>").append(historyMessage.getTo()).append("</to>");
	            builder.append("<from>").append(historyMessage.getFrom()).append("</from>");
	            builder.append("<body>").append(StringUtils.escapeForXML(historyMessage.getBody())).append("</body>");

	            String dateString = FORMATTER.format(historyMessage.getDate());
	            builder.append("<date>").append(dateString).append("</date>");
	            builder.append("</message>");
			}
		}
		return builder.toString();
	}
	
	public void saveChatTranscript2DB(String askername,String body,String expertname){
		TranscriptIQ transcriptIQ = new TranscriptIQ();
		transcriptIQ.setType(IQ.Type.SET);
		transcriptIQ.setTo(ExpertManager.SERVICE + SparkManager.getConnection().getServiceName());
		TranscriptIQ.Item item = new TranscriptIQ.Item();
		item.setAskername(StringUtil.getJidNode(askername));
		item.setBody(body);
		item.setExpertname(expertname);
		item.setLogTime(new Date().getTime());
		item.setUsername(SparkManager.getSessionManager().getBareAddress());
		transcriptIQ.addItem(item);
		SparkManager.getConnection().sendPacket(transcriptIQ);
	}

}
